using complex.Domain;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Mapping.ByCode;

namespace complex.Services
{
    public static class NhibernateConfigurationFactory
    {
        public static ISessionFactory CreateFactory()
        {
            return new Configuration()
                .SessionFactoryName("demo")
                .DataBaseIntegration(db =>
                                         {
                                             db.Dialect<MsSql2005Dialect>();
                                             db.ConnectionStringName = "default";
                                             db.BatchSize = 100;
                                         })
                .MapCustomers()
                .BuildSessionFactory();
        }
    }

    internal static class MapCustomersExtension
    {
        internal static Configuration MapCustomers(this Configuration configuration)
        {
            var mapper = new ModelMapper();
            mapper
                .Class<Customer>(x =>
                                     {
                                         x.Id(c => c.Id, m => m.Generator(Generators.HighLow));
                                         x.Property(c => c.Name);
                                         x.Component(c => c.Address, m =>
                                                                         {
                                                                             m.Property(a => a.Line1);
                                                                             m.Property(a => a.City);
                                                                             m.Property(a => a.State);
                                                                             m.Property(a => a.ZipCode);
                                                                         });
                                     });

            var mappings = mapper.CompileMappingForAllExplicitlyAddedEntities();
            configuration.AddDeserializedMapping(mappings, "customer");

            return configuration;
        }
    }
}